﻿using DoNet.Helper;
using DoNet.Helper.Cach;
using DoNet.Platform.JD.Model;

namespace DoNet.Platform.JD
{
    public class AccessToken
    {
        /// <summary>
        /// 获取Access Token
        /// </summary>
        /// <param name="app_key">应用标识</param>
        /// <param name="app_secret">应用密钥</param>
        /// <param name="code">用户授权后得到code </param>
        /// <returns></returns>
        public static ReturnData GetAccessToken(string app_key, string app_secret, string code)
        {
            ReturnData result = new ReturnData();
            var res = GetAccessTokenCache(app_key, app_secret, code);
            if (res != null)
            {
                if (res.success)
                {
                    result.success = true;
                    string access_token = "";
                    string expires_time = "";
                    string xid = "";
                    var accessTokenBag = JsonHelper.DeserializeObject<AccessTokenBag>(res.data);
                    if (accessTokenBag != null)
                    {
                        expires_time = accessTokenBag.ExpireTime.ToString("yyyy-MM-dd HH:mm:ss:fff");
                        var model = JsonHelper.DeserializeObject<TokenInfo>(JsonHelper.SerializeObject(accessTokenBag.TokenResult));
                        if (model != null)
                        {
                            access_token = model.access_token;
                            xid = model.xid;
                        }
                    }
                    result.data = JsonHelper.SerializeObject(new
                    {
                        xid = xid,
                        access_token = access_token,
                        expires_time = expires_time
                    });
                }
                else
                {
                    result = res;
                }
            }
            else
            {
                result.success = false;
                result.message = "（京东）获取AccessToken失败";
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app_key">应用标识</param>
        /// <param name="app_secret">应用密钥</param>
        /// <param name="code">用户授权后得到code </param>
        /// <returns></returns>
        private static ReturnData GetAccessTokenCache(string app_key, string app_secret, string code)
        {
            ReturnData result = new ReturnData();
            string cacheKey = "JD_AccessToken_" + app_key;

            var obj = MemoryHelper.Get(cacheKey);
            if (obj != null)
            {
                var accessTokenBag = JsonHelper.DeserializeObject<AccessTokenBag>(obj);
                if(accessTokenBag != null)
                {
                    if (accessTokenBag.ExpireTime <= DateTime.Now)
                    {
                        //强制重新获取或者已过期，重新获取
                        var res = GetAccessTokenBag(app_key, app_secret, code);
                        if (res.success)
                        {
                            accessTokenBag = JsonHelper.DeserializeObject<AccessTokenBag>(res.data);
                            if (accessTokenBag != null)
                            {
                                //先删除缓存
                                MemoryHelper.Remove(cacheKey);
                                //加入缓存
                                MemoryHelper.Set(cacheKey, accessTokenBag);

                                result.success = true;
                                result.data = JsonHelper.SerializeObject(accessTokenBag);
                            }
                            else
                            {
                                result.success = false;
                                result.message = "（京东）AccessToken接口返回结果为空！";
                            }
                        }
                        else
                        {
                            result = res;
                        }
                    }
                    else
                    {
                        result.success = true;
                        result.data = JsonHelper.SerializeObject(accessTokenBag);
                    }
                }
                else
                {
                    result.success = false;
                    result.message = "（京东）缓存中的AccessToken为空";
                }
            }
            else
            {
                var res = GetAccessTokenBag(app_key, app_secret, code);
                if (res.success)
                {
                    var accessTokenBag = JsonHelper.DeserializeObject<AccessTokenBag>(res.data);
                    if(accessTokenBag != null)
                    {
                        //加入缓存
                        MemoryHelper.Set(cacheKey, accessTokenBag);

                        result.success = true;
                        result.data = JsonHelper.SerializeObject(accessTokenBag);
                    }
                    else
                    {
                        result.success = false;
                        result.message = "（京东）AccessToken接口返回结果为空！";
                    }
                }
                else
                {
                    result = res;
                }
            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app_key">应用标识</param>
        /// <param name="app_secret">应用密钥</param>
        /// <param name="code">用户授权后得到code </param>
        /// <returns></returns>
        private static ReturnData GetAccessTokenBag(string app_key, string app_secret, string code)
        {
            ReturnData result = new ReturnData();
            var res = TokenApi.GetToken(app_key, app_secret, code);
            if (res != null)
            {
                if (res.success)
                {
                    AccessTokenBag accessTokenBag = new AccessTokenBag();
                    var tokenResult = JsonHelper.DeserializeObject<TokenInfo>(res.data);
                    if (tokenResult != null)
                    {
                        accessTokenBag.TokenResult = tokenResult;
                        accessTokenBag.ExpireTime = DateTime.Now.Add(TimeSpan.FromSeconds(tokenResult.expires_in - 30)); //提前30秒过期

                        result.success = true;
                        result.data = JsonHelper.SerializeObject(accessTokenBag);
                    }
                    else
                    {
                        result.success = false;
                        result.message = "（京东）AccessToken接口返回结果为空！";
                    }
                }
                else
                {
                    result = res;
                }
            }
            else
            {
                result.success = false;
                result.message = "（京东）AccessToken接口返回结果为空！";
            }
            
            return result;
        }
    }
}
